/**
 * Created by Administrator on 2015-04-30.
 */

import model.TestIdModel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

// 扩展 HttpServlet 类
public class TestCaseControl extends HttpServlet {
    TestIdModel testIdModel;
    public void init() throws ServletException
    {
        // 执行必需的初始化
        this.testIdModel = new TestIdModel();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String action = request.getParameter("action");
        String id = request.getParameter("id");
        String ip = request.getRemoteAddr();
        JSONObject jsonObject = new JSONObject();

        id = id + "-" + ip;
        if (action.equals("start")){
            if (testIdModel.addTestId(id)){
                jsonObject.put("result", 1);
                jsonObject.put("message", "id:"+ id +" start to test");
            }else {
                jsonObject.put("result", 0);
                jsonObject.put("message", "id:"+ id +" existed");
            }
        }

        if (action.equals("end")){
            testIdModel.deleteTestId(id);
            jsonObject.put("result", 1);
            jsonObject.put("message", "id:"+ id +" deleted");
        }

        if (action.equals("isEnd")){
            if (testIdModel.isHaveTestId(id)){
                jsonObject.put("result", 0);
                jsonObject.put("message", "id:"+ id +" running");
            }else {
                jsonObject.put("result", 1);
                jsonObject.put("message", "id:"+ id +" seem stop");
            }
        }

//        用于调试，停止所有运行的测试
        if (action.equals("allClear")){
            testIdModel.clearThisMap();
            jsonObject.put("result", 1);
            jsonObject.put("message", "test id all clear");
        }

        PrintWriter out = response.getWriter();
        out.println(jsonObject);
//        debug
        testIdModel.showThisMap();
    }

    public void destroy()
    {
    }
}